package com.xiaobai.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc_v6x.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaobai.Result.R;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;

/**
 * @Author
 * @Description
 * @Date created in 11:29 2025/2/6
 */
@Component
public class MyBlockException implements BlockExceptionHandler {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, String resourceName, BlockException e) throws Exception {
        response.setStatus(439);
        response.setContentType("application/json; charset=UTF-8");
        PrintWriter out = response.getWriter();
        R error = R.error(500, resourceName + "被Sentinel限流了,原因:" + e.getClass());
        out.write(objectMapper.writeValueAsString(error));
        out.flush();
        out.close();
    }
}
